package com.changgou.seckill.service.impl;

import com.changgou.seckill.dao.SeckillGoodsMapper;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SeckillOrderService;
import com.changgou.seckill.task.MultiThreadingCreateOrder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.IdWorker;
import entity.SeckillStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/****
 * @Author:shenkunlin
 * @Description:SeckillOrder业务层接口实现类
 * @Date 2019/6/14 0:16
 *****/
@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private MultiThreadingCreateOrder multiThreadingCreateOrder;

    /**
     * 修改订单状态
     * @param outtradeno 商户订单号
     * @param transaction_id 微信支付订单号
     */
    @Override
    public void updateStatus(String outtradeno, String transaction_id,String time_end,String username){
        //查询订单
        SeckillOrder seckillOrder = seckillOrderMapper.selectByPrimaryKey(outtradeno);
        if (seckillOrder != null){
            //更新订单信息
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = null;
            try {
                date = simpleDateFormat.parse(time_end);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            seckillOrder.setPayTime(date);
            seckillOrder.setStatus("1");
            seckillOrder.setTransactionId(transaction_id);
            seckillOrder.setReceiver(username);
            //更新数据库
            seckillOrderMapper.updateByPrimaryKeySelective(seckillOrder);
            //删除Redis中订单
            redisTemplate.boundHashOps("SeckillOrder").delete(username);
            //删除用户排队信息
            clearQueue(username);
        }

    }


    /**
     * 支付失败，回滚
     * @param outtradeno 商户订单号
     * @param username
     */
    public void deletOrder(String outtradeno,String username){
        //删除订单
        redisTemplate.boundHashOps("SeckillOrder").delete(username);
        //查询用户排队信息
        SeckillStatus userSeckillQuery = (SeckillStatus) redisTemplate.boundHashOps("UserSeckillQuery").get(username);

        //redis回滚-->redis递增-->redis不一定有
        if (userSeckillQuery != null){
            Long goodsId = userSeckillQuery.getGoodsId();
            if (redisTemplate.boundHashOps("SeckillGoodsCount").size()>0){
                //如果redis有
                //更新商品计数库存
                redisTemplate.boundHashOps("SeckillGoodsCount").increment(goodsId, 1);
            }else {
                //如果没有，从数据库中查出
                SeckillGoods seckillGoods = seckillGoodsMapper.selectByPrimaryKey(goodsId);
                //更新数据库库存
                seckillGoods.setStockCount(1);
                seckillGoodsMapper.updateByPrimaryKeySelective(seckillGoods);
                redisTemplate.boundHashOps("SeckillGoodsCount").put(goodsId, 1);
            }

            //队列回滚
            redisTemplate.boundListOps("SeckillGoodsCountList_" + goodsId).leftPush(goodsId);

            //抢单订单数据库回滚
            SeckillOrder seckillOrder = seckillOrderMapper.selectByPrimaryKey(outtradeno);
            if (seckillOrder != null){
                //更新订单信息
                seckillOrder.setStatus("0");
                //更新数据库
                seckillOrderMapper.updateByPrimaryKeySelective(seckillOrder);

            }
            //删除用户排队信息
            clearQueue(username);
        }else {
            throw new RuntimeException("未查到该用户排队信息！");
        }

    }

    /***
     * 清理用户排队信息
     * @param username
     */
    public void clearQueue(String username){
        //清理排队标示
        redisTemplate.boundHashOps("userQueueCount").delete(username);

        //清理抢单标示
        redisTemplate.boundHashOps("UserSeckillQuery").delete(username);
    }

    /**
     * 多线程抢单-排队
     * @param time
     * @param id
     * @param username
     * @return
     */
    @Override
    public Boolean add(String time, Long id, String username) {
        //记录用户排队的次数
        //1.key
        //2.自增的值
        Long queueCount = redisTemplate.boundHashOps("userQueueCount").increment(username, 1);
        if (queueCount>1){
            return false;
        }

        //将抢单信息存入redis队列（左存右取）  List队列
        //Redis单线程下可以实现一秒钟抗150万并发（官方说法）
        SeckillStatus seckillStatus = new SeckillStatus(username, new Date(), 1, id, time);
        redisTemplate.boundListOps("SeckillOrderQueue").leftPush(seckillStatus);
        //同时再存入Hash队列中，用来后续的查询用户抢单状态用
        redisTemplate.boundHashOps("UserSeckillQuery").put(username,seckillStatus);
        //执行异步抢单
        multiThreadingCreateOrder.createOrder();
        return true;
    }

    /**
     * SeckillOrder条件+分页查询
     * @param seckillOrder 查询条件
     * @param page 页码
     * @param size 页大小
     * @return 分页结果
     */
    @Override
    public PageInfo<SeckillOrder> findPage(SeckillOrder seckillOrder, int page, int size){
        //分页
        PageHelper.startPage(page,size);
        //搜索条件构建
        Example example = createExample(seckillOrder);
        //执行搜索
        return new PageInfo<SeckillOrder>(seckillOrderMapper.selectByExample(example));
    }

    /**
     * SeckillOrder分页查询
     * @param page
     * @param size
     * @return
     */
    @Override
    public PageInfo<SeckillOrder> findPage(int page, int size){
        //静态分页
        PageHelper.startPage(page,size);
        //分页查询
        return new PageInfo<SeckillOrder>(seckillOrderMapper.selectAll());
    }

    /**
     * SeckillOrder条件查询
     * @param seckillOrder
     * @return
     */
    @Override
    public List<SeckillOrder> findList(SeckillOrder seckillOrder){
        //构建查询条件
        Example example = createExample(seckillOrder);
        //根据构建的条件查询数据
        return seckillOrderMapper.selectByExample(example);
    }


    /**
     * SeckillOrder构建查询对象
     * @param seckillOrder
     * @return
     */
    public Example createExample(SeckillOrder seckillOrder){
        Example example=new Example(SeckillOrder.class);
        Example.Criteria criteria = example.createCriteria();
        if(seckillOrder!=null){
            // 主键
            if(!StringUtils.isEmpty(seckillOrder.getId())){
                    criteria.andEqualTo("id",seckillOrder.getId());
            }
            // 秒杀商品ID
            if(!StringUtils.isEmpty(seckillOrder.getSeckillId())){
                    criteria.andEqualTo("seckillId",seckillOrder.getSeckillId());
            }
            // 支付金额
            if(!StringUtils.isEmpty(seckillOrder.getMoney())){
                    criteria.andEqualTo("money",seckillOrder.getMoney());
            }
            // 用户
            if(!StringUtils.isEmpty(seckillOrder.getUserId())){
                    criteria.andEqualTo("userId",seckillOrder.getUserId());
            }
            // 创建时间
            if(!StringUtils.isEmpty(seckillOrder.getCreateTime())){
                    criteria.andEqualTo("createTime",seckillOrder.getCreateTime());
            }
            // 支付时间
            if(!StringUtils.isEmpty(seckillOrder.getPayTime())){
                    criteria.andEqualTo("payTime",seckillOrder.getPayTime());
            }
            // 状态，0未支付，1已支付
            if(!StringUtils.isEmpty(seckillOrder.getStatus())){
                    criteria.andEqualTo("status",seckillOrder.getStatus());
            }
            // 收货人地址
            if(!StringUtils.isEmpty(seckillOrder.getReceiverAddress())){
                    criteria.andEqualTo("receiverAddress",seckillOrder.getReceiverAddress());
            }
            // 收货人电话
            if(!StringUtils.isEmpty(seckillOrder.getReceiverMobile())){
                    criteria.andEqualTo("receiverMobile",seckillOrder.getReceiverMobile());
            }
            // 收货人
            if(!StringUtils.isEmpty(seckillOrder.getReceiver())){
                    criteria.andEqualTo("receiver",seckillOrder.getReceiver());
            }
            // 交易流水
            if(!StringUtils.isEmpty(seckillOrder.getTransactionId())){
                    criteria.andEqualTo("transactionId",seckillOrder.getTransactionId());
            }
        }
        return example;
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(Long id){
        seckillOrderMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改SeckillOrder
     * @param seckillOrder
     */
    @Override
    public void update(SeckillOrder seckillOrder){
        seckillOrderMapper.updateByPrimaryKey(seckillOrder);
    }

    /**
     * 根据ID查询SeckillOrder
     * @param id
     * @return
     */
    @Override
    public SeckillOrder findById(Long id){
        return  seckillOrderMapper.selectByPrimaryKey(id);
    }

    /**
     * 查询SeckillOrder全部数据
     * @return
     */
    @Override
    public List<SeckillOrder> findAll() {
        return seckillOrderMapper.selectAll();
    }
}
